/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlCliente;
import Modelo.Cliente;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Damian
 */
public class PnlSeleccionarCliente extends javax.swing.JPanel {

    /**
     * Creates new form PnlSeleccionarCliente
     */
    ArrayList<Cliente> l;
    ControlCliente controlp = new ControlCliente();
    TableRowSorter<TableModel> rs;

    public PnlSeleccionarCliente() {
        initComponents();
        try {
            l = controlp.listar();
        } catch (SQLException ex) {

        }
        tabla.setModel(modelo());
        rs = new TableRowSorter<>(tabla.getModel());
        tabla.setRowSorter(rs);

        txtBuscar.getDocument().addDocumentListener(
                new DocumentListener() {
                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        filtrar();
                    }
                });
    }

        public int seleccionado() throws Exception{
            int i=-1;
            i=tabla.getSelectedRow();
            i=rs.convertRowIndexToModel(i);
            return i;
        }
        public int clienteSeleccionado() throws Exception{
            int i;
            i=Integer.parseInt(((DefaultTableModel)tabla.getModel()).getValueAt(seleccionado(), 0).toString());
            return i;
        }
    private void filtrar() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscar.getText(), 1, 2, 3, 4, 5);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rs.setRowFilter(rf);
    }

    public DefaultTableModel modelo() {
        String[] columnas = {"Historia", "Empresa",
            "Nombres", "Apellidos", "RUC", "Ciudad"};
        DefaultTableModel tablaM = new DefaultTableModel(columnas, 0) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false; //To change body of generated methods, choose Tools | Templates.
            }

        };
        try {
            l = controlp.listar();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        try {
            for (int i = 0; i < l.size(); i++) {
                Cliente p = l.get(i);
                tablaM.addRow(new Object[]{p.getHistoria(), p.getEmpresa(),
                    p.getNombres(), p.getApellidos(), p.getRuc(),p.getCiudad()});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tablaM;
    }
public void actualizar() {
        tabla.setRowSorter(null);
        rs = null;
        tabla.setModel(modelo());
        rs = new TableRowSorter<>(tabla.getModel());
        tabla.setRowSorter(rs);
        filtrar();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        txtBuscar = new org.jdesktop.swingx.JXSearchField();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccionar Cliente"));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/edit-find.png"))); // NOI18N
        jLabel1.setText("Buscar:");

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, "testesasdasdasdasdasdas", null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Código", "Empresa", "Responsable", "Correo", "Ciudad"
            }
        ));
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        // TODO add your handling code here:
        //        int i = tabla.getSelectedRow();
        ////                actualizar();
        ////                filtrar();
        //        DefaultTableModel model = ((DefaultTableModel) tabla.getModel());
        //        System.out.println("i: " + i + "cod: " + model.getValueAt(i, 0));
        //        int c = rs.convertRowIndexToModel(i);
        //        System.out.println("c: " + c + "cod: " + model.getValueAt(c, 0));
    }//GEN-LAST:event_tablaMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    private org.jdesktop.swingx.JXSearchField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
